package cn.lwq.view;

import java.awt.EventQueue;

import javax.swing.JFrame;

import cn.lwq.help.ConfigRead;
import cn.lwq.help.Make;
import cn.lwq.help.MyConnection;
import cn.lwq.mysql.MakeMysql;
import cn.lwq.mysql.MysqlConnection;
import cn.lwq.oracle.MakeOracle;
import cn.lwq.oracle.OracleConnection;

import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;

import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JMenu;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JRadioButton;

/**
 * @since 2017年7月17日
 * @author lwq 719812998@qq.com
 * @description
*/
public class MainView extends JFrame {
	
	private static final long serialVersionUID = 7393704247610875752L;
//	private JPanel contentPane;
	private JTextField ipAddress;
	private JTextField port;
	private JTextField user;
	private JTextField password;
	private JTextField dbName;
	private JTextField tableName;
	private JTextArea textArea01;
	private JTextField dateformat;
	private ButtonGroup jRadioButtonGroup;
	private JComboBox dbType;
	private JRadioButton rdbtnJavaField;
	private JRadioButton rdbtnSql;
	private JRadioButton rdbtnMybatisSet;
	private JRadioButton rdbtnMybatisInsert;
	private JRadioButton rdbtnMybatisUpdate;
	private JCheckBox notNull;
	private JCheckBox length;
	private JCheckBox length2;
	private JCheckBox dateAnn;
	private JCheckBox hump;
	private JComboBox comboBoxNotNull;
	private JCheckBox lblNullMsg;
	private JCheckBox lblLengthMsg;
	
	static MainView frame = null;
	private JTextField nullMsg;
	private JTextField lengthMsg;
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					frame = new MainView();
					frame.setVisible(true);
					frame.readConfig();
				} catch (NullPointerException nullException){
					
				} catch (Exception e) {
					JOptionPane.showMessageDialog(null, e.getMessage() == null ? e : e.getMessage(), "提示", JOptionPane.ERROR_MESSAGE);
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MainView() {
//		setIconImage(Toolkit.getDefaultToolkit().getImage("E:\\JAVA\\workspace\\JavaDBField\\bin\\favicon.ico"));
//		setIconImage(new ImageIcon("favicon.ico").getImage());
		setResizable(false);
		setTitle(ConfigRead.TITLE);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 750, 717);
		setAutoRequestFocus(false);
		setLocationRelativeTo(null);// 设置屏幕中央
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e3) {
				try {
					saveConfig("nothing");
				} catch (Exception e) {
					JOptionPane.showMessageDialog(null, e.getMessage() == null ? e : e.getMessage(), "提示", JOptionPane.ERROR_MESSAGE);
				}
				super.windowClosing(e3);
			}
		});
		getContentPane().setLayout(null);
		
		dbType = new JComboBox();
		dbType.setModel(new DefaultComboBoxModel(new String[] {"Oracle", "Mysql"}));
		dbType.setBounds(64, 13, 101, 21);
		dbType.addActionListener(e -> {
			if(dbType == e.getSource()) {
				if(dbType.getSelectedIndex() == 0){
					port.setText("1521");
				}
				if(dbType.getSelectedIndex() == 1){
					port.setText("3306");
				}
//				JOptionPane.showMessageDialog(null, "", "提示", JOptionPane.ERROR_MESSAGE);
			}
		});
		getContentPane().add(dbType);
		
		JLabel lbl_db = new JLabel("数据库");
		lbl_db.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		lbl_db.setBounds(10, 15, 70, 15);
		getContentPane().add(lbl_db);
		
		JLabel lbl_ip = new JLabel("IP地址");
		lbl_ip.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		lbl_ip.setBounds(202, 15, 70, 15);
		getContentPane().add(lbl_ip);
		
		ipAddress = new JTextField();
		ipAddress.setBounds(251, 13, 297, 21);
		getContentPane().add(ipAddress);
		ipAddress.setColumns(10);
		
		JLabel label = new JLabel("端口");
		label.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		label.setBounds(592, 15, 46, 15);
		getContentPane().add(label);
		
		port = new JTextField();
		port.setColumns(10);
		port.setBounds(628, 13, 108, 21);
		port.setText("1521");
		getContentPane().add(port);
		
		JLabel label_1 = new JLabel("用户名");
		label_1.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		label_1.setBounds(10, 54, 70, 15);
		getContentPane().add(label_1);
		
		user = new JTextField();
		user.setColumns(10);
		user.setBounds(64, 52, 101, 21);
		getContentPane().add(user);
		
		JLabel label_2 = new JLabel("密码");
		label_2.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		label_2.setBounds(214, 54, 46, 15);
		getContentPane().add(label_2);
		
		password = new JTextField();
		password.setColumns(10);
		password.setBounds(251, 52, 189, 21);
		getContentPane().add(password);
		
		JLabel label_3 = new JLabel("数据实例名");
		label_3.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		label_3.setBounds(484, 54, 91, 15);
		getContentPane().add(label_3);
		
		dbName = new JTextField();
		dbName.setColumns(10);
		dbName.setBounds(560, 52, 176, 21);
		getContentPane().add(dbName);
		
		JSeparator separator = new JSeparator();
		separator.setBounds(10, 89, 726, 9);
		getContentPane().add(separator);
		
		JLabel label_4 = new JLabel("表名");
		label_4.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		label_4.setBounds(10, 108, 46, 15);
		getContentPane().add(label_4);
		
		tableName = new JTextField();
		tableName.setColumns(10);
		tableName.setBounds(49, 106, 147, 21);
		getContentPane().add(tableName);
		
		JButton btnClick = new JButton("Click");
		btnClick.setFont(new Font("微软雅黑", Font.PLAIN, 12));
		btnClick.setBounds(628, 104, 108, 25);
		btnClick.addActionListener(new DoAction());
		getContentPane().add(btnClick);
		
		// 一个文本输入框，带滚动条
		JScrollPane scrollPane01 = new JScrollPane();
		scrollPane01.setBounds(10, 249, 726, 403);
		getContentPane().add(scrollPane01);
		textArea01 = new JTextArea();
		textArea01.setFont(new Font("新宋体", Font.PLAIN, 13));
		scrollPane01.setViewportView(textArea01);
		
		notNull = new JCheckBox("非空注解");
		notNull.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		notNull.setBounds(10, 133, 83, 23);
		notNull.addChangeListener(e -> {
			if(notNull.isSelected()) {
				//JOptionPane.showMessageDialog(null, , "提示", JOptionPane.ERROR_MESSAGE);
				comboBoxNotNull.setEnabled(true);
				lblNullMsg.setEnabled(true);
			} else {
				comboBoxNotNull.setEnabled(false);
				lblNullMsg.setSelected(false);
				lblNullMsg.setEnabled(false);
			}
		});
		getContentPane().add(notNull);
		
		length = new JCheckBox("长度注解");
		length.setToolTipText("数字最大值9个9");
		length.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		length.setBounds(10, 158, 83, 23);
		length.addChangeListener(e -> {
			if(!length.isSelected()) {
				length2.setSelected(false);
				length2.setEnabled(false);
				lblLengthMsg.setSelected(false);
				lblLengthMsg.setEnabled(false);
			} else {
				length2.setEnabled(true);
				lblLengthMsg.setEnabled(true);
			}
		});
		getContentPane().add(length);
		
		dateAnn = new JCheckBox("日期注解");
		dateAnn.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		dateAnn.setBounds(10, 183, 83, 23);
		dateAnn.addChangeListener(e -> {
			if(dateAnn.isSelected()) dateformat.setEnabled(true);
			else dateformat.setEnabled(false);
		});
		getContentPane().add(dateAnn);
		
		length2 = new JCheckBox("字符长度除2");
		length2.setEnabled(false);
		length2.setToolTipText("所有字符串类型的长度都会除2");
		length2.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		length2.setBounds(95, 158, 101, 23);
		getContentPane().add(length2);
		
		dateformat = new JTextField();
		dateformat.setEnabled(false);
		dateformat.setText("yyyy-MM-dd HH:mm:ss");
		dateformat.setColumns(10);
		dateformat.setBounds(99, 184, 139, 21);
		getContentPane().add(dateformat);
		
		jRadioButtonGroup = new ButtonGroup();
		
		rdbtnJavaField = new JRadioButton("Java Field");
		rdbtnJavaField.setSelected(true);
		rdbtnJavaField.setFont(new Font("微软雅黑", Font.PLAIN, 12));
		rdbtnJavaField.setToolTipText("Java Field");
		rdbtnJavaField.setBounds(10, 208, 87, 23);
		getContentPane().add(rdbtnJavaField);
		jRadioButtonGroup.add(rdbtnJavaField);
		
		rdbtnSql = new JRadioButton("SQL结果");
		rdbtnSql.setToolTipText("");
		rdbtnSql.setFont(new Font("微软雅黑", Font.PLAIN, 12));
		rdbtnSql.setBounds(96, 208, 87, 23);
		getContentPane().add(rdbtnSql);
		jRadioButtonGroup.add(rdbtnSql);
		
		hump = new JCheckBox("驼峰别名");
		hump.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		hump.setBounds(214, 105, 83, 23);
		getContentPane().add(hump);
		
		rdbtnMybatisSet = new JRadioButton("MyBatis Set");
		rdbtnMybatisSet.setToolTipText("");
		rdbtnMybatisSet.setFont(new Font("微软雅黑", Font.PLAIN, 12));
		rdbtnMybatisSet.setBounds(185, 208, 101, 23);
		getContentPane().add(rdbtnMybatisSet);
		jRadioButtonGroup.add(rdbtnMybatisSet);
		
		rdbtnMybatisInsert = new JRadioButton("MyBatis Insert");
		rdbtnMybatisInsert.setToolTipText("");
		rdbtnMybatisInsert.setFont(new Font("微软雅黑", Font.PLAIN, 12));
		rdbtnMybatisInsert.setBounds(289, 208, 116, 23);
		getContentPane().add(rdbtnMybatisInsert);
		jRadioButtonGroup.add(rdbtnMybatisInsert);
		
		rdbtnMybatisUpdate = new JRadioButton("MyBatis Update");
		rdbtnMybatisUpdate.setToolTipText("");
		rdbtnMybatisUpdate.setFont(new Font("微软雅黑", Font.PLAIN, 12));
		rdbtnMybatisUpdate.setBounds(407, 208, 125, 23);
		getContentPane().add(rdbtnMybatisUpdate);
		jRadioButtonGroup.add(rdbtnMybatisUpdate);
		
		comboBoxNotNull = new JComboBox();
		comboBoxNotNull.setEnabled(false);
		comboBoxNotNull.setModel(new DefaultComboBoxModel(new String[] {"NotNull", "NotBlank", "NotEmpty"}));
		comboBoxNotNull.setBounds(99, 134, 97, 21);
		getContentPane().add(comboBoxNotNull);
		
		lblNullMsg = new JCheckBox("Null Msg");
		lblNullMsg.setEnabled(false);
		lblNullMsg.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		lblNullMsg.setBounds(214, 133, 83, 23);
		lblNullMsg.addChangeListener((e2) -> {
			if(lblNullMsg.isSelected()) nullMsg.setEnabled(true);
			else nullMsg.setEnabled(false);
		});
		getContentPane().add(lblNullMsg);
		
		nullMsg = new JTextField();
		nullMsg.setEnabled(false);
		nullMsg.setText(ConfigRead.MESSAGE_NOTNULL_VALUE);
		nullMsg.setColumns(10);
		nullMsg.setBounds(323, 134, 147, 21);
		getContentPane().add(nullMsg);
		
		lengthMsg = new JTextField();
		lengthMsg.setEnabled(false);
		lengthMsg.setText(ConfigRead.MESSAGE_LENGTH_VALUE);
		lengthMsg.setColumns(10);
		lengthMsg.setBounds(323, 159, 147, 21);
		getContentPane().add(lengthMsg);
		
		lblLengthMsg = new JCheckBox("Length Msg");
		lblLengthMsg.setEnabled(false);
		lblLengthMsg.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		lblLengthMsg.setBounds(214, 158, 101, 23);
		lblLengthMsg.addChangeListener(e -> {
			if(lblLengthMsg.isSelected()) lengthMsg.setEnabled(true);
			else lengthMsg.setEnabled(false);
		});
		getContentPane().add(lblLengthMsg);
		
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		JMenu menu_edit = new JMenu("编辑");
		menu_edit.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		menuBar.add(menu_edit);
		
		JMenuItem menuSaveConfig = new JMenuItem("保存配置");
		menuSaveConfig.setFont(new Font("微软雅黑", Font.PLAIN, 12));
		menuSaveConfig.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e2) {
				try {
					saveConfig();
				} catch (Exception e) {
					JOptionPane.showMessageDialog(null, e.getMessage() == null ? e : e.getMessage(), "提示", JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		menu_edit.add(menuSaveConfig);
		
		JMenuItem menuLoadConfig = new JMenuItem("加载配置");
		menuLoadConfig.setFont(new Font("微软雅黑", Font.PLAIN, 12));
		menuLoadConfig.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e2) {
				try {
					readConfig();
				} catch (Exception e) {
					JOptionPane.showMessageDialog(null, e.getMessage() == null ? e : e.getMessage(), "提示", JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		menu_edit.add(menuLoadConfig);
		
		/*
		JMenuItem menuDefaultConfig = new JMenuItem("加载默认配置");
		menuDefaultConfig.setFont(new Font("微软雅黑", Font.PLAIN, 12));
		menuDefaultConfig.addActionListener(e -> {
			if(e.getSource() == menuDefaultConfig) {
				dbType.setSelectedIndex(0);
				ipAddress.setText("dev.db.eyedsion.com");
				port.setText("1521");
				user.setText("adx_uat");
				password.setText("123456");
				dbName.setText("orcl");
				tableName.setText("dis_instorage");
				
//				dbType.setSelectedIndex(1);
//				ipAddress.setText("localhost");
//				port.setText("3306");
//				user.setText("root");
//				password.setText("root");
//				dbName.setText("test");
//				tableName.setText("helloworld");
			}
		});
		menu_edit.add(menuDefaultConfig);
		*/
		
	}
	
	private void saveConfig(Object...objects) throws Exception {
		ConfigRead configRead = new ConfigRead();
		ConfigRead.DATABASE_DBNAME = dbName.getText();
		ConfigRead.DATABASE_IPADDRESS = ipAddress.getText();
		ConfigRead.DATABASE_PORT = port.getText();
		ConfigRead.DATABASE_USER = user.getText();
		ConfigRead.DATABASE_PASSWORD = password.getText();
		ConfigRead.DATABASE_TABLE = tableName.getText();
		ConfigRead.DATABASE_DB = dbType.getSelectedItem().toString().toUpperCase();
		configRead.saveConfig();
		if(objects.length == 0) {
			JOptionPane.showMessageDialog(null, "保存完成", "提示", JOptionPane.WARNING_MESSAGE);
		}
	}
	
	private void readConfig() throws Exception {
		ConfigRead configRead = new ConfigRead();
		configRead.readConfig();
		dbType.setSelectedIndex(ConfigRead.DATABASE_DB.equalsIgnoreCase(ConfigRead.ORACLE) ? 0 : 1);
		ipAddress.setText(ConfigRead.DATABASE_IPADDRESS);
		port.setText(ConfigRead.DATABASE_PORT);
		user.setText(ConfigRead.DATABASE_USER);
		password.setText(ConfigRead.DATABASE_PASSWORD);
		dbName.setText(ConfigRead.DATABASE_DBNAME);
		tableName.setText(ConfigRead.DATABASE_TABLE);
	}
	
	private boolean checkMessageFormat() {
		String str = "";
		String tmp = "%s";
		String msg = "非空注解的自定义消息中必须且只能有一个“ [%s] ”，如“ "+ConfigRead.MESSAGE_NOTNULL_VALUE+" ”";
		if(lblNullMsg.isSelected()) {
			str = nullMsg.getText();
			if(str.indexOf(tmp) == -1) {
				JOptionPane.showMessageDialog(null, msg, "提示", JOptionPane.WARNING_MESSAGE);
				return false;
			}
			String[] strs = str.split(tmp);
			if(strs.length != 2) {
				JOptionPane.showMessageDialog(null, msg, "提示", JOptionPane.WARNING_MESSAGE);
				return false;
			}
		}
		msg = "长度注解自定义消息中必须且只能有2个“ [%s] ”(第一个为字段，第二个为长度值)，如“ "+ConfigRead.MESSAGE_LENGTH_VALUE+" ”";
		if(lblLengthMsg.isSelected()) {
			str = lengthMsg.getText();
			if(str.indexOf(tmp) == -1) {
				JOptionPane.showMessageDialog(null, msg, "提示", JOptionPane.WARNING_MESSAGE);
				return false;
			}
			String[] strs = str.split(tmp);
			if(strs.length != 3) {
				JOptionPane.showMessageDialog(null, msg, "提示", JOptionPane.WARNING_MESSAGE);
				return false;
			}
		}
		return true;
	}
	
	class DoAction implements ActionListener {
		
		private MyConnection connection = null;
		
		@Override
		public void actionPerformed(ActionEvent evnent) {
			if(!checkMessageFormat()) {
				return;
			}
			readThisConfig();
			textArea01.setText("");
			if("".equals(tableName.getText())) {
				JOptionPane.showMessageDialog(null, "表名不能为空", "提示", JOptionPane.WARNING_MESSAGE);
				tableName.setText("");
				return;
			}
			try {
				if(ConfigRead.NOW_DB.equals(ConfigRead.ORACLE)) {
					connection = new OracleConnection();
					Make make = new MakeOracle();
					make.setConnection(connection.getConnection());
					if(rdbtnJavaField.isSelected()) {
						textArea01.setText(make.makeJavaField().toString());
					} else if(rdbtnSql.isSelected()) {
						textArea01.setText(make.makeSqlField().toString());
					} else if(rdbtnMybatisSet.isSelected()){
						textArea01.setText(make.makeMybatisSet().toString());
					} else if(rdbtnMybatisInsert.isSelected()){
						textArea01.setText(make.makeMybatisInsert().toString());
					} else if(rdbtnMybatisUpdate.isSelected()){
						textArea01.setText(make.makeMybatisUpdate().toString());
					}
				}
				if(ConfigRead.NOW_DB.equals(ConfigRead.MYSQL)) {
					connection = new MysqlConnection();
					Make make = new MakeMysql();
					make.setConnection(connection.getConnection());
					if(rdbtnJavaField.isSelected()) {
						textArea01.setText(make.makeJavaField().toString());
					} else if(rdbtnSql.isSelected()) {
						textArea01.setText(make.makeSqlField().toString());
					} else if(rdbtnMybatisSet.isSelected()){
						textArea01.setText(make.makeMybatisSet().toString());
					} else if(rdbtnMybatisInsert.isSelected()){
						textArea01.setText(make.makeMybatisInsert().toString());
					} else if(rdbtnMybatisUpdate.isSelected()){
						textArea01.setText(make.makeMybatisUpdate().toString());
					}
				}
				if("//共[0]个字段".equals(textArea01.getText())) {
					JOptionPane.showMessageDialog(null, "没有取到数据，请检查表名或者库名（MySql的表名要区分大小写）", "提示", JOptionPane.WARNING_MESSAGE);
				}
			} catch (Exception e) {
				JOptionPane.showMessageDialog(null, e.getMessage() == null ? e : e.getMessage(), "提示", JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
			}
		}
		
		private void readThisConfig() {
			ConfigRead.DATABASE_DBNAME = dbName.getText();
			ConfigRead.DATABASE_IPADDRESS = ipAddress.getText();
			ConfigRead.DATABASE_PORT = port.getText();
			ConfigRead.DATABASE_USER = user.getText();
			ConfigRead.DATABASE_PASSWORD = password.getText();
			ConfigRead.NOW_DB = dbType.getSelectedItem().toString().toUpperCase();
			///
			ConfigRead.TABLE_NAME = tableName.getText().replaceAll("\\s*", "");
			tableName.setText(ConfigRead.TABLE_NAME);
			if(ConfigRead.NOW_DB.equals(ConfigRead.ORACLE)) {
				ConfigRead.TABLE_NAME = ConfigRead.TABLE_NAME.toUpperCase();
			}
			ConfigRead.ANN_NOTNULL = notNull.isSelected();
			ConfigRead.ANN_LENGTH = length.isSelected();
			ConfigRead.ANN_LENGTH_2 = length2.isSelected();
			ConfigRead.ANN_DATE = dateAnn.isSelected();
			ConfigRead.ANN_DATE_FORMAT = dateformat.getText();
			ConfigRead.HUMP = hump.isSelected();
			ConfigRead.NOT_NULL_VALUE = comboBoxNotNull.getSelectedItem().toString();
			///
			ConfigRead.MESSAGE_NOTNULL = lblNullMsg.isSelected();
			ConfigRead.MESSAGE_NOTNULL_VALUE = nullMsg.getText();
			ConfigRead.MESSAGE_LENGTH = lblLengthMsg.isSelected();
			ConfigRead.MESSAGE_LENGTH_VALUE = lengthMsg.getText();
			
		}
	}
}



